package xyz.scootaloo.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * 缓存
 * @author flutterdash@qq.com
 * @since 2021/3/27 11:00
 */
public class Cache {

    private final Map<String, Object> cache;
    public Cache() {
        cache = new HashMap<>();
    }

    public <T> T getCacheOrElse(String key, Supplier<T> supplier) {
        Optional<T> optional = get(key);
        if (optional.isPresent())
            return optional.get();
        T value = supplier.get();
        put(key, value);
        return value;
    }

    public <T> T put(String key, T value) {
        cache.put(key, value);
        return value;
    }

    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> Optional<T> get(String key) {
        Object value = cache.get(key);
        if (value == null)
            return Optional.empty();
        return Optional.of((T) value);
    }

}
